import React, { useState } from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { langs } from '@uiw/codemirror-extensions-langs';
import styles from './index.less';
import { InfoCircleOutlined } from '@ant-design/icons';

interface IProps {
  value: string;
  /** onChange 回调， 输出 json */
  onChange?: (json: string) => void;
  /**占位符 */
  placeholder?: string;
  /**编辑器高度 */
  height?: string;
  /**只读模式 */
  readonly?: boolean;
  /** 验证结果 */
  verifyRes?: (res: boolean) => void;
}

export default function JsonInput({
  value = '',
  placeholder,
  height,
  readonly,
  onChange,
  verifyRes,
}: IProps) {
  const [jsonString, setJsonString] = useState(value);
  const [errorTips, setErrorTips] = useState('');
  const verifyJson = () => {
    if (jsonString === '') return;
    try {
      const result = JSON.stringify(JSON.parse(jsonString), null, '\t');
      setErrorTips('');
      return result;
    } catch (error) {
      setErrorTips('JSON语法有错误，请修改');
    }
  };
  return (
    <div className={styles['json-container']}>
      <div className={styles['json-input']}>
        <CodeMirror
          className={styles.json}
          value={jsonString}
          height={height}
          theme={'light'}
          placeholder={placeholder}
          readOnly={readonly}
          extensions={[langs.json()]}
          onChange={(value) => {
            setJsonString(value);
            onChange?.(value);
          }}
          onBlur={() => {
            if (typeof verifyJson() === 'string') {
              setJsonString(verifyJson() as 'string');
              verifyRes?.(true);
            } else {
              verifyRes?.(false);
            }
          }}
        />
        {errorTips && (
          <div className={styles['error-tips']}>
            <InfoCircleOutlined style={{ marginRight: '4px' }} />
            {errorTips}
          </div>
        )}
      </div>
    </div>
  );
}
